<template>
  <div>
    <!-- <button @click="edit">修改</button> -->
    <n-card :bordered="false" class="proCard">
      <BasicForm
        :showAdvancedButton="false"
        @register="register"
        @submit="handleSelect"
        @reset="handleReset"
      >
        <template #statusSlot="{ model, field }">
          <n-input v-model:value="model[field]" />
        </template>
      </BasicForm>

      <BasicTable
        :columns="columns"
        :request="loadDataTable"
        ref="actionRef"
        :actionColumn="actionColumn"
        @update:checked-row-keys="onCheckedRow"
        :scroll-x="1090"
      >
        <template #tableTitle>
          <n-button @click="showModal('', true)"> 添加 </n-button>
        </template>
      </BasicTable>
    </n-card>
    <!-- 新增弹窗 -->
    <basicModal @register="modalRegister" ref="modalRef" class="basicModal" @on-ok="handleAddUser">
      <template #default>
        <BasicForm
          @register="registerModal"
          @reset="handleReset"
          class="basicForm"
          @submit="handleSubmit"
          :rules="rules"
        >
          <template #statusSlot="{ model, field }">
            <n-input v-model:value="model[field]" />
          </template>
        </BasicForm>
      </template>
    </basicModal>
    <n-modal
      v-model:show="showModalCode"
      preset="dialog"
      title="二维码数量"
      positive-text="确认"
      @positive-click="submitCallback"
      @negative-click="cancelCallback"
    >
      <div>
        <n-input-number
          placeholder="请输入生成二维码数量"
          :min="1"
          v-model:value="CreateCodeMum"
          clearable
        />
      </div>
    </n-modal>
  </div>
</template>
<script lang="ts" setup>
  import { h, reactive, ref } from 'vue';
  import { BasicTable, TableAction } from '@/components/Table';
  import { BasicForm, useForm } from '@/components/Form/index';
  import { getUserList, addUser, delUser, edit, userDisable, getProduce } from '@/api/api';
  import {
    schemasUser,
    schemasUserModal,
    schemasWorkshop,
    schemasExternalUnit,
    schemasExternalworkShop,
    formattedDate,
  } from '@/config/options';
  import { basicModal, useModal } from '@/components/Modal';
  import { type FormRules } from 'naive-ui';
  import { useMessage, useDialog } from 'naive-ui';
  const actionRef = ref();
  const formModal = ref();
  const message = useMessage();
  const dialog = useDialog();
  const showCode = ref(true);
  const CreateCodeMum = ref();
  const showModalCode = ref(false);
  const rules = {
    id: {
      required: true,
      message: '请输入id',
      trigger: 'input',
    },
    unit: {
      required: true,
      message: '请输入单位名称',
      trigger: 'input',
    },
    workshop: {
      required: true,
      message: '请输入车间名称',
      trigger: 'input',
    },
    username: {
      required: true,
      message: '请输入账号',
      trigger: 'input',
    },
    password: {
      required: true,
      message: '请输入密码',
      trigger: 'input',
    },
    codes_num: {
      required: true,
      message: '请输入二维码数量',
      type: 'Number',
      trigger: ['input', 'blur'],
    },
    max_num: {
      required: true,
      message: '请输入',
      trigger: 'input',
    },
    annual_check: {
      required: true,
      type: 'date',
      message: '请选择年检时间',
      trigger: ['change', 'blur'],
    },
    expiration_time: {
      required: true,
      message: '请选择到期时间',
      trigger: ['change', 'blur'],
    },
  };
  const actionColumn = reactive({
    width: 200,
    title: '操作',
    key: 'action',
    fixed: 'right',
    render(record) {
      return h(TableAction as any, {
        style: 'text',
        actions: [
          {
            label: '编辑',
            onClick: showModal.bind(null, record, false),
          },
          {
            label: '删除',
            onClick: handleDelete.bind(null, record),
          },
          {
            label: record.status ? '禁用' : '启用',
            onClick: handleForbidden.bind(null, record),
          },
          {
            label: '生成二维码',
            onClick: handleCreateCode.bind(null, record),
          },
        ],
      });
    },
  });
  const [register, { getFieldsValue, setFieldsValue }] = useForm({
    gridProps: { cols: '1 s:1 m:2 l:3 xl:4 2xl:4' },
    labelWidth: 80,
    schemas: schemasUser,
  });
  const isAdd = ref(true);
  const props = defineProps<{
    columns: Array;
    userType: string;
  }>();
  const columns = reactive(props.columns);
  const userType = ref(props.userType);
  // 获取表格数据
  const loadDataTable = async (res) => {
    const data = await getUserList({ ...getFieldsValue(), ...res, user_type: userType.value });
    return data;
  };
  function reloadTable() {
    actionRef.value.reload();
  }
  function handleReset(values: Recordable) {}
  // 查询
  function handleSelect(values: Recordable) {
    console.log(values);
    reloadTable();
  }
  const [modalRegister, { openModal, closeModal, setSubLoading }] = useModal({
    title: '添加账号',
  });
  const schemasModal = reactive([]);
  if (userType.value == 3) {
    schemasModal.value = schemasWorkshop;
  } else if (userType.value == 4) {
    schemasModal.value = schemasExternalUnit;
  } else if (userType.value == 5) {
    schemasModal.value = schemasExternalworkShop;
  } else {
    schemasModal.value = schemasUserModal;
  }
  const [registerModal, { submit, resetFields }] = useForm({
    gridProps: { cols: 1 },
    collapsedRows: 3,
    labelWidth: 150,
    isFull: false,
    layout: 'horizontal',
    submitButtonText: '提交预约',
    showActionButtonGroup: false,
    schemas: schemasModal.value,
  });
  const id = ref(0); //账号id
  const showModal = (record, flag) => {
    flag ? (isAdd.value = true) : (isAdd.value = false);
    let names = [];
    if (!flag) {
      id.value = record.id;
      if (userType.value == 1 || userType.value == 2) {
        names = [record.unit, record.username, record.password, record.codes_num];
      } else if (userType.value == 3) {
        names = [record.unit, record.workshop, record.username, record.password];
      } else if (userType.value == 4) {
        names = [record.unit, record.username, record.password, record.codes_num, record.max_num];
      } else if (userType.value == 5) {
        names = [record.id, record.workshop, record.name, record.username, record.password];
      }
    }
    schemasModal.value.forEach((obj, index) => {
      obj.defaultValue = names[index];
    });
    openModal();
  };
  async function handleAddUser() {
    const formRes = await submit();
    if (formRes) {
      // 发送添加请求
      if (isAdd.value) {
        adduser(formRes);
      } else {
        handleEdit(formRes);
      }
    } else {
      message.error('验证失败，请填写完整信息');
      setSubLoading(false);
    }
  }
  // 添加账号
  const adduser = async (formRes) => {
    if (userType.value == 4) {
      console.log(formattedDate(formRes.expiration_time));
      formRes.expiration_time = formattedDate(formRes.expiration_time);
      formRes.annual_check = formattedDate(formRes.annual_check);
    }
    await addUser({ ...getFieldsValue(), ...formRes, user_type: userType.value })
      .then((res) => {
        setSubLoading(false);
        closeModal();
        reloadTable();
        message.info('添加成功');
      })
      .catch((err) => {
        setSubLoading(false);
      });
  };

  // 编辑账号
  const handleEdit = async (formRes: any) => {
    if (userType.value == 4) {
      formRes.expiration_time = formattedDate(formRes.expiration_time);
      formRes.annual_check = formattedDate(formRes.annual_check);
    }
    await edit({ ...getFieldsValue(), ...formRes, user_type: userType.value, id: id.value })
      .then((res) => {
        setSubLoading(false);
        closeModal();
        reloadTable();
        message.info('修改成功');
      })
      .catch((err) => {
        setSubLoading(false);
      });
  };
  // 删除账号
  function handleDelete(record) {
    console.log(record);
    dialog.warning({
      title: '提示',
      content: `您想删除${record.username}`,
      positiveText: '确定',
      negativeText: '取消',
      onPositiveClick: () => {
        delUser({ id: record.id }).then((res) => {
          console.log(res);
          reloadTable();
          message.success('删除成功');
        });
      },
      onNegativeClick: () => {},
    });
  }
  function handleForbidden(record) {
    let status = record.status ? '启用' : '禁用';
    dialog.warning({
      title: '提示',
      content: `是否确认${status}？`,
      positiveText: '确定',
      negativeText: '取消',
      onPositiveClick: async () => {
        let result = await userDisable({ id: record.id, status: !record.status });
        message.success(result.status ? '已禁用' : '已启用');
        reloadTable();
      },
      onNegativeClick: () => {},
    });
  }
  // 生成二维码方法发
  const submitCallback = async () => {
    if (CreateCodeMum.value) {
      let result = await getProduce({ num: CreateCodeMum.value, id: id.value });
      message.success('生成成功');
    } else {
      message.success('请输入要生成的二维码数量');
    }
  };
  //  生成二维码
  const handleCreateCode = (record) => {
    id.value = record.id;
    showModalCode.value = true;
  };
</script>
